package com.xique.common.core.utils;

import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 *
 * @author xique
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    /**时间精确到毫秒*/
    public static String YYYYMMDDHHMMSSSSS="yyyyMMddHHmmssSSS";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    public static String MM_DD_HH_MM_SS = "MM-dd HH:mm:ss";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate() {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate() {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime() {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow() {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format) {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date) {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date) {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts) {
        try {
            return new SimpleDateFormat(format).parse(ts);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime() {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str) {
        if (str == null) {
            return null;
        }
        try {
            return parseDate(str.toString(), parsePatterns);
        } catch (ParseException e) {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate() {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算两个时间差
     */
    public static String getDatePoor(Date endDate, Date nowDate) {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - nowDate.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 获取当前日期的前几天日期
     *
     * @param days
     * @return
     */
    public static String getPrevioudDate(int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.DATE, 0 - days);
        Date d = c.getTime();
        return dateTime(d);
    }

    /**
     * 计算某日期之后几天对应的日期
     *
     * @param startDate
     * @param days
     * @return
     */
    public static Date getNextDate(Date startDate, int days) {
        Calendar c = Calendar.getInstance();
        c.setTime(startDate);
        c.add(Calendar.DATE, days);
        Date d = c.getTime();
        return d;
    }


    /**
     * 根据时间 和时间格式 校验是否正确
     *
     * @param length 校验的长度
     * @param sDate  校验的日期
     * @param format 校验的格式
     * @return
     */
    public static boolean isLegalDate(int length, String sDate, String format) {
        int legalLen = length;
        if ((sDate == null) || (sDate.length() != legalLen)) {
            return false;
        }
        DateFormat formatter = new SimpleDateFormat(format);
        try {
            Date date = formatter.parse(sDate);
            return sDate.equals(formatter.format(date));
        } catch (Exception e) {
            return false;
        }
    }


    /**
     * 日期转星期
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime, String[] week) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        if (week.length > 0) {
            weekDays = week;
        }
        Calendar cal = Calendar.getInstance(); // 获得一个日历
        Date datet = null;
        try {
            datet = f.parse(datetime);
            cal.setTime(datet);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1; // 指示一个星期中的某天。
        if (w < 0) {
            w = 0;
        }
        return weekDays[w];
    }

    public static String getLastMonths(int i) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

        Calendar c = Calendar.getInstance();

        c.setTime(new Date());

        c.add(Calendar.MONTH, -i);

        Date m = c.getTime();

        return sdf.format(m);

    }


    /**
     * @description: 获取当前UTC时间戳（减去时区偏移量） 单位秒
     * @author caogq
     * @date 2021/11/4 9:56
     * @version 1.0
     */

    public static Long getCurrentUTCTimestamp() {
        long time = (System.currentTimeMillis() - TimeZone.getDefault().getRawOffset()) / 1000;
        return Long.valueOf(time);
    }

    /**
     * @description: 获取当前UTC时间戳（减去时区偏移量） 单位秒
     * @author caogq
     * @date 2021/11/4 9:56
     * @version 1.0
     */

    public static Long getCurrentTimestamp() {
        long time = System.currentTimeMillis() / 1000;
        return Long.valueOf(time);
    }

    /**
     * 计算两个日期相隔的月份数
     *
     * @param begin
     * @param end
     * @return
     * @create xl.liu
     */
    public static int getMonthsDiff(Date begin, Date end) {
        long diff = end.getTime() - begin.getTime();
        long nd = 1000 * 24 * 60 * 60;
        // 计算差多少天
        long day = diff / nd;
        long month = day / 30;
        int months = Math.round(month);
        return months;
    }

    /**
     * @description: 获取过去第几天的日期
     * @author caogq
     * @date 2021/12/28 10:34
     * @version 1.0
     */

    public static Date getPastDay(int past) {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past);

        return calendar.getTime();
    }

    /**
     * 获取startDate日期后month月的日期
     *
     * @param startDate 开始日期
     * @param month     几个月后
     * @return
     */
    public static Date getMonthDate(Date startDate, int month) {
        LocalDateTime localDateTime = startDate.toInstant()
                .atZone(ZoneId.systemDefault())
                .toLocalDateTime().plusMonths(month);
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());
        return date;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDaysByMillisecond(Date date1, Date date2) {
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24));
        return days;
    }

    /**
     * 通过时间秒毫秒数判断两个时间的间隔
     *
     * @param date1
     * @param date2
     * @return
     */
    public static long getMillisecondDiff(Date date1, Date date2) {
        long second = (long) (date2.getTime() - date1.getTime());
        return second;
    }

    public static double getHouseDiff(Date date1, Date date2) {
        double hour = (double) ((date2.getTime() - date1.getTime()) / (1000 * 60 * 60));
        return hour;
    }


    /**
     * 获取当前的年
     */
    public static Integer getYears() {
        Calendar calendar = new GregorianCalendar(TimeZone.getDefault());
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 获取当前的月
     */
    public static Integer getMonth() {
        Calendar calendar = new GregorianCalendar(TimeZone.getDefault());
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前天
     */
    public static Integer getDay() {
        Calendar calendar = new GregorianCalendar(TimeZone.getDefault());
        return calendar.get(Calendar.DAY_OF_MONTH);
    }

    /**
     * 获取昨天的日期 - 年-月-日
     */
    public static String getYesterday() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, -24);
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 获取当前小时
     */
    public static Integer getHour() {
        Calendar cal = Calendar.getInstance();
        return cal.get(Calendar.HOUR_OF_DAY);
    }

    /**
     * 获取过去第几天的日期
     */
    public static String getPastDate(int past) {
        Calendar calendar1 = Calendar.getInstance();
        SimpleDateFormat sdf1 = new SimpleDateFormat(YYYY_MM_DD);
        calendar1.add(Calendar.DATE, -past);
        return sdf1.format(calendar1.getTime());
    }

    /**
     * 指定日期减去指定天数
     */
    public static String getPastDate(Date date, int past) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -past);
        SimpleDateFormat sdf1 = new SimpleDateFormat(YYYY_MM_DD);
        return sdf1.format(calendar.getTime());
    }

    public static Date getStartOfDay(Date date) {

        return DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, DateFormatUtils.format(date, DateUtils.YYYY_MM_DD) + " 00:00:00");
    }

    public static Date getEndOfDay(Date date) {
        return DateUtils.dateTime(DateUtils.YYYY_MM_DD_HH_MM_SS, DateFormatUtils.format(date, DateUtils.YYYY_MM_DD) + " 23:59:59");
    }

    public static Long getRemainSecondsOneDay(Date currentDate) {
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
                .withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault());
        Long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return seconds;
    }


    /**
     * @description: 根据传入的时间转换成对应的天/时/分/秒
     * @author: HdongSun
     * @date: 2022/9/30 16:00
     * @param: [time]
     * @return: java.lang.String
     **/
    public static String getSecondToDate(Long time) {
        String strTime = null;
        Long days = time / (60 * 60 * 24);
        Long hours = (time % (60 * 60 * 24)) / (60 * 60);
        Long minutes = (time % (60 * 60)) / 60;
        Long seconds = time % 60;
        if (days > 0) {
            strTime = days + "天" + hours + "小时" + minutes + "分钟";
        } else if (hours > 0) {
            strTime = hours + "小时" + minutes + "分钟";
        } else if (minutes > 0) {
            strTime = minutes + "分钟" + seconds + "秒";
        } else {
            strTime = seconds + "秒";
        }
        return strTime;
    }
}
